import {Modal, Icon, Button, message, Row, Col, Table, Dropdown, Form, Menu} from 'antd';
// import Row from '../../_antd1.11.2/Row';
// import Col from '../../_antd1.11.2/Col';
// import Modal from '../../_antd1.11.2/Modal';
// import Button from '../../_antd1.11.2/Button';
// import Icon from '../../_antd1.11.2/Icon';
// import message from '../../_antd1.11.2/message'
// import Table from '../../_antd1.11.2/table';
// import Dropdown from '../../_antd1.11.2/dropdown';
// import Menu from '../../_antd1.11.2/menu';
// import Form from '../../_antd1.11.2/form';
const MenuItem = Menu.Item;
const FormItem = Form.Item;

import WeaTools from '../wea-tools';
import WeaNewScroll from '../wea-new-scroll';
import WeaSelect from '../wea-select';
import WeaBrowser from '../wea-browser';
import WeaScope from '../wea-scope';

import isEqual from 'lodash/isEqual';

//国际化 zxt- 20170419
const defaultLocale = {
  	total: '共',
  	totalUnit: '条',
  	operates: '操作',
  	delete: '删除',
  	customColSave: '保存',
  	customColCancel: '取消',
};


class Main extends React.Component {
	//国际化 zxt- 20170419
	static contextTypes = {
	    antLocale: React.PropTypes.object,
	}
	getLocale() {
	    let locale = {};
	    if (this.context.antLocale && this.context.antLocale.Table) {
	    	locale = this.context.antLocale.WeaTableEdit;
	    }
	    return { ...defaultLocale, ...locale, ...this.props.locale };
  	}
    constructor(props) {
        super(props);
        this.state = {
        	mainKey: '',
        	//table
        	datas: [],
        	selectedRowKeys: [],
        	pageSize: 10,
        	//modal
        	visible: false,
        	addDatas: [],
        	addDatasInit: [],
        }
        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);
		this.doAdd = this.doAdd.bind(this);
    }
    componentDidMount() {
	    const { datas = [], conditions = [], columns = [] } = this.props;
      	this.setState({ datas });
      	!(!`${conditions}` || !`${columns}`) && this.doSet(conditions, columns);
    }
    componentWillReceiveProps(nextProps){
	    let { datas = [], conditions = [], columns = [] } = this.props,
    		nextDatas = nextProps.datas || [],
    		nextConditions = nextProps.conditions || [],
    		nextColumns = nextProps.columns || [];
    	if(!isEqual(datas, nextDatas)){
    		this.setState({
    			datas: this.addKeytoDatas(nextDatas),
    		});
    	}
    	if((!isEqual(conditions, nextConditions) || !isEqual(columns, nextColumns)) && !(!`${nextConditions}` || !`${nextColumns}`)){
    		this.doSet(nextConditions, nextColumns);
    	}
    }
    render() {
    	let { title = '', width = 460, scollHeight = 0, conditions = [] } = this.props,
    		{ datas, visible, selectedRowKeys } = this.state,
       		buttons = [
	            <Button key="submit" type="primary" size="large" onClick={this.onOk} >保 存</Button>,
	            <Button key="back" type="ghost" size="large" onClick={this.onCancel}>取 消</Button>
	       	];
        return (
            <div className='wea-table-edit wea-table-edit-ismodal' style={scollHeight ? { height: scollHeight } : {}}>
            	<Row className="wea-table-edit-title" >
					<Col>
						{ title }
						<Button type="primary" disabled={!`${selectedRowKeys}`} title='删除' size="small" onClick={this.doDelete.bind(this,selectedRowKeys)} ><Icon type="minus" /></Button>
						<Button type="primary" disabled={!`${conditions}`}  title='新增' size="small" onClick={this.doAdd}><Icon type="plus" /></Button>
					</Col>
	            </Row>
                <WeaNewScroll height={scollHeight ? scollHeight - 45 : '100%'}>
                    <Table
	                	columns={this.getColumns()}
	                	dataSource={datas}
	                	pagination={this.getPagination()}
	                	rowSelection={this.getRowSelection()}
	                />
                </WeaNewScroll >
	            <Modal wrapClassName="wea-hr-muti-input"
		            title={this.getTitle()}
		            width={width}
		            maskClosable={false}
		            visible={visible}
		            onCancel={this.onCancel}
		            footer={buttons}
		        >
		            {this.getAddComponent()}
	            </Modal>
            </div>
        );
    }
    //添加数据
    doAddComponentChange(type, key, value, list, url){
    	let { conditions } = this.props,
    		{ addDatas, mainKey } = this.state,
    		_addDatas = [].concat(addDatas);
    	if(value){
	    	if(type === 'BROWSER') {
	    		let ids = value.split(',');
	    		let addData = {..._addDatas[0]};
	    		_addDatas = [];
	    		ids.map((id,i) => {
	    			let _addData = {...addData};
	    			_addData[key] = id;
	    			_addData[key + 'span'] = list[i]['name'] || list[i]['lastname'];
	    			_addData[key + 'url'] = `${url}${id}`;
	    			_addDatas.push(_addData);
	    		});
	    	}
		    if(type === 'SELECT') {
		    	const init = key === mainKey;
	    		_addDatas = _addDatas.map(addData => {
	    			let _addData = init ? {} : {...addData};
	    			let hasSec = false;
	    			init && conditions[1][value].map(condition => {
	    				if(condition.conditionType === 'INPUT_INTERVAL' && condition.domkey[0] === 'seclevel')
	    					hasSec = true;
	    				if(condition.conditionType === 'SELECT')
		    				condition.options.map(o => {
		    					if(o.selected === true){
		    						_addData[condition.domkey[0]] = o.key;
		    						_addData[condition.domkey[0] + 'span'] = o.showname;
		    					}
		    				});
	    			});
	    			if(hasSec) _addData.seclevel = '0-100';
	    			list.map(l => {
	    				if(l.key === value){
	    					_addData[key] = value;
	    					_addData[key + 'span'] = l.showname;
	    					if(url)	_addData[key + 'url'] = `${url}${value}`;
	    				}
	    			})
	    			return _addData
	    		})
		    }
		    if(type === 'INPUT_INTERVAL'){
		    	_addDatas = _addDatas.map(addData => {
		    		let _addData = {...addData};
					_addData[key] = `${value}-${list}`;
					//_addData[key + 'span'] = url;
		    		return _addData
		    	})
		    }
    	}
	    this.setState({addDatas:_addDatas})
    }
    getAddComponent(){
    	let { conditions } = this.props,
    		{ addDatas, mainKey } = this.state;
    	if(!`${conditions}` || !mainKey) return null;
    	const index = addDatas[0][mainKey];
    	return (
    		<div style={{ padding: 20 }}>
    			<FormItem
                    label={conditions[0].label}
                    labelCol={{span: conditions[0].labelcol}}
                    wrapperCol={{span: conditions[0].fieldcol}}>
                        <WeaSelect
                        	value={index}
    						onChange={v => this.doAddComponentChange('SELECT',conditions[0].domkey[0],v,conditions[0].options)}
		                    options= {conditions[0].options}
		                />
                </FormItem>
				{
					conditions[1][index].map(condition => {
						let showDropMenu = false;
						let replaceDatas = [];
						let startValue = 0;
						let endValue = 100;
						if(condition.conditionType === 'BROWSER') {
							if(condition.browserConditionParam)
								showDropMenu = condition.browserConditionParam.type=='4' || condition.browserConditionParam.type=='164';//部门分部显示维度菜单
							addDatas.map(addData => {
								addData[condition.domkey[0]] && replaceDatas.push({
									id:addData[condition.domkey[0]] || '',
									name: addData[`${condition.domkey[0]}span`] || '',
								})
							});
						}
						if(condition.conditionType === 'INPUT_INTERVAL' && addDatas[0][condition.domkey[0]]){
							const value = addDatas[0][condition.domkey[0]].split('-');
							startValue = Number(value[0]);
							endValue = Number(value[1]);
						}
						return (
							<FormItem
			                    label={condition.label}
			                    labelCol={{span: condition.labelcol}}
			                    wrapperCol={{span: condition.fieldcol}}>
			    					{
			    						condition.conditionType === 'SELECT' &&
				    					<WeaSelect
				    						value={addDatas[0][condition.domkey[0]] || '1'}
				    						onChange={v => this.doAddComponentChange('SELECT',condition.domkey[0],v,condition.options)}
						                    options= {condition.options}
						                />
			    					}
			    					{
			    						condition.conditionType === 'BROWSER' &&
			    						<WeaBrowser {...condition.browserConditionParam}
			    							replaceDatas={replaceDatas}
			    							showDropMenu={showDropMenu}
			    							onChange={(v, name, list) => this.doAddComponentChange('BROWSER',condition.domkey[0],v,list,condition.browserConditionParam.linkUrl)}
			    						/>

			    					}
			    					{
			    						condition.conditionType === 'INPUT_INTERVAL' &&
			    						<WeaScope
			    							min={[0,100]}
			    							max={[0,100]}
			    							domkey={condition.domkey}
			    							startValue={startValue}
			    							endValue={endValue}
			    							onChange={(start, end) => this.doAddComponentChange('INPUT_INTERVAL',condition.domkey[0],start,end)}
			    						/>
			    					}
			                </FormItem>
						)
					})
				}
			</div>
    	)
    }
    //util
    doSet(conditions, columns){
		const mainKey = columns[0].dataIndex;
		let key = '', showname = '';
		conditions[0].options.map(o => {
			if(o.selected){
				key = o.key;
				showname = o.showname;
			}
		})
		if(!key){
			key = conditions[0].options[0].key;
			showname = conditions[0].options[0].showname;
		}
		let addDatas = mainKey ? [{ [mainKey]: key, [`${mainKey}span`]: showname }] : [];
		this.setState({ mainKey, addDatas, addDatasInit: addDatas });
    }
    addKeytoDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i
			return _data
		})
		return _datas
	}
    deleteKeyfromDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			delete _data.key
			return _data
		})
		return _datas
	}
    //table
    getColumns(){
    	let { columns } = this.props,
			_columns = [].concat(columns);
		_columns = _columns.map(col => {
			let _col = { ...col };
			_col.render = ( text, record, index ) => {
				return (record[`${_col.dataIndex}span`] || record[_col.dataIndex])
			}
			return _col
		});
		const locale = this.getLocale();
		`${_columns}` && _columns.push({
			title: '',
			dataIndex: 'ops',
			key: 'ops',
			width: 80,
            className:"wea-table-operates",
            render: ( text, record, index )=> {
            	const menu = (
            		<Menu>
                        <MenuItem>
	                        <a href='javascript:void(0);' onClick={this.doDelete.bind(this,[record.key])}>{locale.delete}</a>
	                    </MenuItem>
                    </Menu>
            	)
            	return (
                    <div className='wea-table-edit-ismodal-ops'>
                        <Dropdown overlay={menu}>
                            <span>
                                {locale.operates} <Icon type="caret-down" />
                            </span>
                        </Dropdown>
                    </div>
                )
            }
		});
		return _columns
    }
    getPagination() {
		return false
	}
    getRowSelection(){
		let { columns } = this.props,
			{ selectedRowKeys } = this.state;
		if(!`${columns}`) return null
		const rowSelection = {
			selectedRowKeys,
			onChange: (sRowKeys, selectedRows) => {
				this.setState({selectedRowKeys : sRowKeys});
			}
		}
		return rowSelection
	}
    //btns
    doAdd(){
    	this.setState({visible: true})
    }
    doDelete(keys){
    	let { onChange } = this.props,
    		{ datas } = this.state,
    		_datas = [].concat(datas);
    	keys.map(key => {
    		_datas = _datas.filter(_data => _data.key !== key)
    	});
    	_datas = this.addKeytoDatas(_datas);
    	this.setState({
    		datas: _datas,
    		selectedRowKeys: [],
    	});
    	typeof onChange === 'function' && onChange(this.deleteKeyfromDatas(_datas));
    }
    //modal
    getTitle(){
    	const { modalTitle = ''} = this.props;
    	return (
    		<Row>
                <Col span="8" style={{ paddingLeft:20, lineHeight:'48px', minHeight: 48 }}>
                    { modalTitle }
                </Col>
            </Row>
    	)
    }
    onOk(){
    	let { onChange } = this.props,
    		{ datas, addDatas, addDatasInit } = this.state,
    		_datas = [].concat(datas),
    		_addDatas = [].concat(addDatas);
    	_addDatas = _addDatas.map((addData, i)=> {
    		let _addData = {...addData};
    		_addData.key = datas.length + i;
    		return _addData
    	})
    	if(_addDatas.length > 0){
    		_datas = _datas.concat(_addDatas)
    		this.setState({
    			visible: false,
    			datas: _datas,
    			addDatas: addDatasInit,
    		});
    		typeof onChange === 'function' && onChange(this.deleteKeyfromDatas(_datas));
    	}else{
    		message.warning('数据不能为空！',500);
    	}
    }
    onCancel(){
    	const { addDatasInit } = this.state;
    	this.setState({visible: false, addDatas: addDatasInit})
    }
}

export default Main;